package com.sgb.kjwl.view.ui.fragment.chat;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.hotpot.core.interfaces.IMessageCallBack;
import com.hotpot.sdk.HotpotManager;
import com.hotpot.sdk.room.entity.receive.SessionListReceive;
import com.hotpot.sdk.utils.RoomDaoHelper;
import com.qgb.zutils.JsonUtils;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FrChatNewsViewBinding;
import com.sgb.kjwl.model.entity.chat.NewsMenuEntity;
import com.sgb.kjwl.view.ui.adapter.NewsPagerAdapter;
import com.sgb.kjwl.viewmodel.chat.ChatNewsModel;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.im.immodel.IMUtils;
import com.swgk.core.util.ResolutionUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息-消息模块界面
 * Create by LiWei  2021/11/10
 */
public class ChatNewsFragment extends AppLazyFragment {

    private FrChatNewsViewBinding binding;
    private ChatNewsModel viewModel;
    private LinearLayout.LayoutParams layoutParams;
    private int tabWidth;
    private boolean isLoadingCompleted = false;

    public static ChatNewsFragment newInstance() {
        ChatNewsFragment dialog = new ChatNewsFragment();
        Bundle bundle = new Bundle();
        dialog.setArguments(bundle);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fr_chat_news_view, container, false);
        viewModel = new ViewModelProvider(getActivity()).get(ChatNewsModel.class);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        String timelineId = MkvUtils.get().getString(MkvUtils.get().CacheUserCenterMenu, CacheMarker.IM_NOTICE_TIME_ID, "");
        RoomDaoHelper.getInstaner().getSessionListDao().getListLiveData().observe(getActivity(), new Observer<List<SessionListReceive>>() {
            @Override
            public void onChanged(List<SessionListReceive> sessionListReceives) {
                String timelineId = MkvUtils.get().getString(MkvUtils.get().CacheUserCenterMenu, CacheMarker.IM_NOTICE_TIME_ID, "");
                if (TextUtils.isEmpty(timelineId)) {
                    if (sessionListReceives != null && sessionListReceives.size() > 0) {
                        for (SessionListReceive entity : sessionListReceives) {
                            if ("IM_SYSTEM_ACCOUNT_TOTAL".equals(entity.getSenderId())) {
                                MkvUtils.get().putString(MkvUtils.get().CacheUserCenterMenu, CacheMarker.IM_NOTICE_TIME_ID, entity.getTimelineId());
                                viewModel.getNoticeMenuList(entity.getTimelineId(), "1");
                                break;
                            }
                        }
                    }
                }
            }
        });
        //处理经营帮通知消息数目刷新
        IMUtils.getInstance().handleNewsInterception(2, new IMUtils.MsgHandleInterception() {
            @Override
            public void onChangedPassword() {

            }

            @Override
            public void onRefreshUnRead() {
                viewModel.getNewNoticeMenuList(timelineId, "1");
            }

        });

        viewModel.menuList.observe(getActivity(), new Observer<List<NewsMenuEntity>>() {
            @Override
            public void onChanged(List<NewsMenuEntity> newsMenuEntities) {
                initTabMenu(newsMenuEntities);
            }
        });
        viewModel.newMenuList.observe(getActivity(), new Observer<List<NewsMenuEntity>>() {
            @Override
            public void onChanged(List<NewsMenuEntity> newsMenuEntities) {
                customTabMenuView(newsMenuEntities);
            }
        });

        layoutParams = (LinearLayout.LayoutParams) binding.indicationLine.getLayoutParams();
        tabWidth = ResolutionUtil.getScreenWidth(getActivity()) / 5;
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                layoutParams.leftMargin = (int) ((tabWidth - ResolutionUtil.dp2px(getActivity(), 25)) / 2 + positionOffset * tabWidth + position * tabWidth);
                binding.indicationLine.setLayoutParams(layoutParams);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //初始化菜单界面
        if (TextUtils.isEmpty(timelineId)) {
            initTabMenu(viewModel.getMenuList());
        } else {
            viewModel.getNoticeMenuList(timelineId, "1");
        }
    }

    @Override
    protected void onLazyLoad() {

    }

    private void initTabMenu(List<NewsMenuEntity> list) {
        binding.tabLayout.clearOnTabSelectedListeners();
        binding.tabLayout.removeAllTabs();
        List<Fragment> fragmentList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                fragmentList.add(NewsChildFragment.newInstance());
                continue;
            }
            fragmentList.add(NewsNoticeFragment.newInstance(list.get(i).getType()));
        }
        NewsPagerAdapter adapter = new NewsPagerAdapter(getChildFragmentManager(), fragmentList, list);
        binding.viewPager.setAdapter(adapter);
        binding.tabLayout.setupWithViewPager(binding.viewPager);
        binding.viewPager.setOffscreenPageLimit(1);
        binding.viewPager.setCurrentItem(0);
        isLoadingCompleted = true;
        for (int i = 0; i < list.size(); i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_tab_news_menu, null, false);
            binding.tabLayout.getTabAt(i).setCustomView(view);
            TextView tv = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_name);
            TextView tvUnReadNum = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_unReadNum);
            tv.setText(list.get(i).getName());
            if (list.get(i).getUnReadNum() != 0) {
                tvUnReadNum.setText(list.get(i).getUnReadNum() + "");
                tvUnReadNum.setVisibility(View.VISIBLE);
            } else {
                tvUnReadNum.setVisibility(View.GONE);
            }
            if (i == 0) {
                tv.setSelected(true);
                tvUnReadNum.setVisibility(View.GONE);
            }
        }
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_name);
                TextView tvUnReadNum = tab.getCustomView().findViewById(R.id.tv_unReadNum);
                tv.setSelected(true);
                tvUnReadNum.setVisibility(View.GONE);
                tv.invalidate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_name);
                tv.setSelected(false);
                tv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void customTabMenuView(List<NewsMenuEntity> list) {
        if (isLoadingCompleted) {
            for (int i = 0; i < list.size(); i++) {
                TextView tvUnReadNum = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_unReadNum);
                if (list.get(i).getUnReadNum() != 0) {
                    tvUnReadNum.setText(list.get(i).getUnReadNum() + "");
                    tvUnReadNum.setVisibility(View.VISIBLE);
                } else {
                    tvUnReadNum.setVisibility(View.GONE);
                }
                tvUnReadNum.invalidate();
            }
            binding.viewPager.setCurrentItem(0);
        }
    }
}
